﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.SqlServer.Server;
using Newtonsoft.Json.Linq;
using Serilog;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using TMI85303.UI.Messages;
using TMI85303.Utils;

namespace TMI85303.UI.UserControls
{
    /// <summary>
    /// DebugControl.xaml 的交互逻辑
    /// </summary>
    public partial class DebugControl : UserControl
    {
        public DebugControl()
        {
            InitializeComponent();
        }
    }

    public enum ContinuousRW { READ, WRITE }

    public partial class DebugVM : ObservableObject
    {
        public List<string> TimeLists { get; set; } = new() {"10","100","200", "500","1000","1500","2000" };

        [ObservableProperty]
        private string? slaveAddr = "55";

        [ObservableProperty]
        private bool checked1 = false;

        [ObservableProperty]
        private bool checked2 = false;

        [ObservableProperty]
        private bool checked3 = false;

        [ObservableProperty]
        private bool checked4 = false;

        [ObservableProperty]
        private bool checked5 = false;

        [ObservableProperty]
        private bool checked6 = false;

        [ObservableProperty]
        private bool checked7 = false;

        [ObservableProperty]
        private bool checked8 = false;

        [ObservableProperty]
        private bool checked9 = false;

        [ObservableProperty]
        private bool checked10 = false;

        [ObservableProperty]
        private bool checked11 = false;

        [ObservableProperty]
        private bool checked12 = false;

        [ObservableProperty]
        private bool checked13 = false;

        [ObservableProperty]
        private bool checked14 = false;


        [ObservableProperty]
        private string? addr1;
        [ObservableProperty]
        private string? addr2;
        [ObservableProperty]
        private string? addr3;
        [ObservableProperty]
        private string? addr4;
        [ObservableProperty]
        private string? addr5;
        [ObservableProperty]
        private string? addr6;
        [ObservableProperty]
        private string? addr7;
        [ObservableProperty]
        private string? addr8;
        [ObservableProperty]
        private string? addr9;
        [ObservableProperty]
        private string? addr10;
        [ObservableProperty]
        private string? addr11;
        [ObservableProperty]
        private string? addr12;
        [ObservableProperty]
        private string? addr13;
        [ObservableProperty]
        private string? addr14;

        [ObservableProperty]
        private string? data1;
        [ObservableProperty]
        private string? data2;
        [ObservableProperty]
        private string? data3;
        [ObservableProperty]
        private string? data4;
        [ObservableProperty]
        private string? data5;
        [ObservableProperty]
        private string? data6;
        [ObservableProperty]
        private string? data7;
        [ObservableProperty]
        private string? data8;
        [ObservableProperty]
        private string? data9;
        [ObservableProperty]
        private string? data10;
        [ObservableProperty]
        private string? data11;
        [ObservableProperty]
        private string? data12;
        [ObservableProperty]
        private string? data13;
        [ObservableProperty]
        private string? data14;

        [ObservableProperty]
        private ContinuousRW rwType = ContinuousRW.READ;

        [ObservableProperty]
        private string intervalRW = "500";

        [ObservableProperty]
        private bool intervalRWEnable = true;

        [ObservableProperty]
        private bool rwTypeEnable = true;

        [ObservableProperty]
        private string operaContent = "开始";

        [ObservableProperty]
        private bool isStartChecked = false;

        [ObservableProperty]
        private string i2CClockSpeed = "400";

        private readonly DispatcherTimer rwTime = new();

        public DebugVM()
        {
            rwTime.Interval = TimeSpan.FromMilliseconds(500);
            rwTime.Tick += (s, e) => OnReadWrite();
        }

        [RelayCommand]
        private void SetColck()
        {
            if (uint.TryParse(I2CClockSpeed, out uint newVal))
            {
                newVal = newVal < 60 ? 60 : (newVal > 1000 ? 1000 : newVal);
                I2CClockSpeed = newVal.ToString();
                WeakReferenceMessenger.Default.Send<UpdateI2CClock, int>(new(newVal), (int)MesgToken.MainWindowToken);
            }
            else
            {
                MessageBox.Show("请输入60~1000的非负整数！");
            }
        }

        private void OnReadWrite()
        {
            if(RwType == ContinuousRW.READ)
            {
                ReadOnce();
            }
            else
            {
                WriteOnce();
            }
        }


        [RelayCommand]
        private void ReadOnce()
        {
            if (Checked1 && ushort.TryParse(Addr1, NumberStyles.HexNumber, null, out var addrVal)) Data1 = Read(addrVal).ToString("X4");
            if (Checked2 && ushort.TryParse(Addr2, NumberStyles.HexNumber, null, out addrVal)) Data2 = Read(addrVal).ToString("X4");
            if (Checked3 && ushort.TryParse(Addr3, NumberStyles.HexNumber, null, out addrVal)) Data3 = Read(addrVal).ToString("X4");
            if (Checked4 && ushort.TryParse(Addr4, NumberStyles.HexNumber, null, out addrVal)) Data4 = Read(addrVal).ToString("X4");
            if (Checked5 && ushort.TryParse(Addr5, NumberStyles.HexNumber, null, out addrVal)) Data5 = Read(addrVal).ToString("X4");
            if (Checked6 && ushort.TryParse(Addr6, NumberStyles.HexNumber, null, out addrVal)) Data6 = Read(addrVal).ToString("X4");
            if (Checked7 && ushort.TryParse(Addr7, NumberStyles.HexNumber, null, out addrVal)) Data7 = Read(addrVal).ToString("X4");
            if (Checked8 && ushort.TryParse(Addr8, NumberStyles.HexNumber, null, out addrVal)) Data8 = Read(addrVal).ToString("X4");
            if (Checked9 && ushort.TryParse(Addr9, NumberStyles.HexNumber, null, out addrVal)) Data9 = Read(addrVal).ToString("X4");
            if (Checked10 && ushort.TryParse(Addr10, NumberStyles.HexNumber, null, out addrVal)) Data10 = Read(addrVal).ToString("X4");
            if (Checked11 && ushort.TryParse(Addr11, NumberStyles.HexNumber, null, out addrVal)) Data11 = Read(addrVal).ToString("X4");
            if (Checked12 && ushort.TryParse(Addr12, NumberStyles.HexNumber, null, out addrVal)) Data12 = Read(addrVal).ToString("X4");
            if (Checked13 && ushort.TryParse(Addr13, NumberStyles.HexNumber, null, out addrVal)) Data13 = Read(addrVal).ToString("X4");
            if (Checked14 && ushort.TryParse(Addr14, NumberStyles.HexNumber, null, out addrVal)) Data14 = Read(addrVal).ToString("X4");
        }

        [RelayCommand]
        private void WriteOnce()
        {
            if (Checked1 && ushort.TryParse(Addr1, NumberStyles.HexNumber, null, out var addrVal) && ushort.TryParse(Data1, NumberStyles.HexNumber, null, out var dataVal)) Write(addrVal, dataVal);
            if (Checked2 && ushort.TryParse(Addr2, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data2, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked3 && ushort.TryParse(Addr3, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data3, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked4 && ushort.TryParse(Addr4, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data4, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked5 && ushort.TryParse(Addr5, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data5, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked6 && ushort.TryParse(Addr6, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data6, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked7 && ushort.TryParse(Addr7, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data7, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked8 && ushort.TryParse(Addr8, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data8, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked9 && ushort.TryParse(Addr9, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data9, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked10 && ushort.TryParse(Addr10, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data10, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked11 && ushort.TryParse(Addr11, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data11, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked12 && ushort.TryParse(Addr12, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data12, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked13 && ushort.TryParse(Addr13, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data13, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
            if (Checked14 && ushort.TryParse(Addr14, NumberStyles.HexNumber, null, out addrVal) && ushort.TryParse(Data14, NumberStyles.HexNumber, null, out dataVal)) Write(addrVal, dataVal);
        }

        [RelayCommand]
        private void ReadWriteContinue(object parameter)
        {
            if (parameter is not bool isChecked) return;
            if(IsStartChecked)
            {
                if(!int.TryParse(IntervalRW, out var time) || time < 10 || time > 2000)
                {
                    MessageBox.Show("请输入10~2000范围的整数！");
                    IsStartChecked = false;
                    return;
                }
                else
                {
                    rwTime.Interval = TimeSpan.FromMilliseconds(time);
                }

            }

            if (isChecked)
            {
                rwTime.Start();
                OperaContent = "停止";
                IntervalRWEnable = false;
                RwTypeEnable = false;
            }
            else
            {
                rwTime.Stop();
                OperaContent = "开始";
                IntervalRWEnable = true;
                RwTypeEnable = true;
            }
        }

        [RelayCommand]
        private void ClearData()
        {
            Data1  = "";
            Data2  = "";
            Data3  = "";
            Data4  = "";
            Data5  = "";
            Data6  = "";
            Data7  = "";
            Data8  = "";
            Data9  = "";
            Data10 = "";
            Data11 = "";
            Data12 = "";
            Data13 = "";
            Data14 = "";
        }

        private static byte addrBit = 0x08;



        private int Read(ushort readAddr)
        {
            if(!byte.TryParse(SlaveAddr,NumberStyles.HexNumber, null, out var slaveAddrVal))
            {
                Log.Information("从机地址解析错误");
                return -1;
            }

            byte[] dataOut = new byte[3];
            int result = default(int);

            if (ReadWrite.i2cRead(slaveAddrVal, addrBit, readAddr, dataOut, 2))
            {
                result = (dataOut[0] << 8) + dataOut[1];
                Log.Information(" 读" + readAddr.ToString() + "：0x" + result.ToString("X4") + "(" + result.ToString() + ")\r\n");

            }
            return result;
        }

        private bool Write(ushort writeAddr, int writeData)
        {
            if (!byte.TryParse(SlaveAddr, NumberStyles.HexNumber, null, out var slaveAddrVal))
            {
                Log.Information("从机地址解析错误");
                return false;
            }

            byte[] array = new byte[3];

            array[0] = (byte)((writeData >> 8) & 0xFF);
            array[1] = (byte)(writeData & 0xFF);


            if (ReadWrite.i2cWrite(slaveAddrVal, addrBit, writeAddr, array, 2))
            {
                Log.Information(" 写" + writeAddr.ToString() + "：0x" + writeData.ToString("X4") + "(" + writeData.ToString() + ")\r\n");

                return true;
            }
            return false;
        }

    }

}
